<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - 数码商城</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            background-color: #f4f4f4;
            color: #333;
        }

        /* Header Styles */
        .header {
            background-color: #fff;
            padding: 1rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
        }

        .nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #ff4400;
        }

        .nav-links {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .nav-links a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            max-width: 900px;
            margin: 80px auto 20px;
            padding: 20px;
            display: flex;
            gap: 20px;
        }

        /* Sidebar */
        .sidebar {
            width: 200px;
            background: white;
            border-radius: 4px;
            padding: 20px;
            height: fit-content;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .user-info {
            text-align: center;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
            margin-bottom: 20px;
        }

        .avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin-bottom: 10px;
            object-fit: cover;
            border: 2px solid #ffebee;
        }

        .username {
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 18px;
            color: #333;
        }

        .user-level {
            color: #ff4400;
            font-size: 12px;
            background: #fff5f0;
            padding: 3px 8px;
            border-radius: 10px;
            display: inline-block;
        }

        .menu-list {
            list-style: none;
        }

        .menu-item {
            padding: 10px;
            cursor: pointer;
            border-radius: 4px;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
        }

        .menu-item:hover {
            background-color: #fff5f0;
            color: #ff4400;
        }

        .menu-item.active {
            background-color: #fff5f0;
            color: #ff4400;
            font-weight: 500;
        }

        /* Profile Content */
        .profile-content,
        .orders-content {
            flex: 1;
            background: white;
            border-radius: 4px;
            padding: 30px;
            display: none;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .profile-content.active,
        .orders-content.active {
            display: block;
        }

        .section-title {
            font-size: 20px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #666;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background: #fafafa;
        }

        .form-group input:focus {
            border-color: #ff4400;
            outline: none;
            background: #fff;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }

        .save-button {
            background-color: #ff4400;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
            font-weight: 500;
        }

        .save-button:hover {
            background-color: #ff5500;
            box-shadow: 0 2px 8px rgba(255, 68, 0, 0.3);
        }

        /* Order History */
        .order-list {
            margin-top: 30px;
        }

        .order-item {
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.3s;
        }

        .order-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            margin-bottom: 10px;
        }

        .order-number {
            color: #666;
        }

        .order-status {
            color: #ff4400;
            font-weight: 500;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            background: #fff5f0;
        }

        .order-status.not-shipped {
            background: #fff3e0;
            color: #f57c00;
        }

        .order-status.shipped {
            background: #e8f5e9;
            color: #388e3c;
        }

        .order-status.completed {
            background: #e8f5e8;
            color: #388e3c;
        }

        .order-status.cancelled {
            background: #ffebee;
            color: #d32f2f;
        }

        .order-products {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }

        .order-product {
            display: flex;
            gap: 10px;
            align-items: center;
            padding: 10px;
            border: 1px solid #f5f5f5;
            border-radius: 4px;
            background: #fafafa;
            flex: 1;
            min-width: 200px;
        }

        .order-product img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            background: #f0f0f0;
        }

        .order-total {
            text-align: right;
            color: #ff4400;
            font-weight: bold;
            font-size: 18px;
            margin-top: 10px;
        }

        /* Loading */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 40px;
            flex-direction: column;
        }

        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-left-color: #ff4400;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .loading-text {
            color: #666;
            font-size: 14px;
        }

        .error-message {
            background: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
            text-align: center;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
            }

            .form-row {
                flex-direction: column;
                gap: 0;
            }

            .order-product {
                min-width: 100%;
            }
        }
    </style>
</head>

<body>
    <!-- Header -->
    <header class="header">
        <nav class="nav">
            <div class="logo">数码商城</div>
            <div class="nav-links">
                <a href="product.html"><i class="fas fa-home"></i> 首页</a>
                <a href="#"><i class="fas fa-shopping-cart"></i> 购物车</a>
                <a href="#" style="color: #ff4400;"><i class="fas fa-user"></i> 个人中心</a>
            </div>
        </nav>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="user-info">
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="用户头像" class="avatar" id="userAvatar">
                <div class="username" id="username">加载中...</div>
                <div class="user-level" id="userLevel">--</div>
            </div>
            <ul class="menu-list">
                <li class="menu-item active" data-content="profile">
                    <i class="fas fa-user"></i>
                    <span>个人资料</span>
                </li>
                <li class="menu-item" data-content="orders">
                    <i class="fas fa-shopping-bag"></i>
                    <span>我的订单</span>
                </li>

            </ul>
        </aside>

        <!-- Profile Content -->
        <div class="profile-content active" id="profileContent">
            <h2 class="section-title">个人资料</h2>
            <div class="loading" id="profileLoading">
                <div class="spinner"></div>
                <div class="loading-text">正在从后端加载用户数据...</div>
            </div>
            <div id="errorContainer" class="error-message" style="display: none;"></div>
            <form id="profileForm" style="display: none;">
                <div class="form-row">
                    <div class="form-group">
                        <label for="usernameInput">用户名</label>
                        <input type="text" id="usernameInput" name="username" required readonly>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="email">邮箱</label>
                        <input type="email" id="email" name="email" required readonly>
                    </div>
                    <div class="form-group">
                        <label for="phone">手机号</label>
                        <input type="tel" id="phone" name="phone" required readonly>
                    </div>
                </div>
                <div class="form-group">
                    <label for="address">地址</label>
                    <input type="text" id="address" name="address" required readonly>
                </div>
                <button type="button" class="save-button" id="editButton">
                    <i class="fas fa-edit"></i> <span id="editButtonText">编辑资料</span>
                </button>
                <button type="button" class="save-button" id="saveButton"
                    style="display: none; background-color: #4CAF50;">
                    <i class="fas fa-save"></i> 保存更改
                </button>
            </form>
        </div>

        <!-- Orders Content -->
        <div class="orders-content" id="ordersContent">
            <h2 class="section-title">最近订单</h2>
            <div class="loading" id="ordersLoading">
                <div class="spinner"></div>
                <div class="loading-text">正在加载订单数据...</div>
            </div>
            <div id="ordersContainer" style="display: none;"></div>
        </div>
    </main>

    <script>
        // 从后端API获取用户数据
        async function fetchUserData() {
            try {
                const response = await fetch('userInfo');
                if (!response.ok) {
                    throw new Error('获取用户信息失败: ' + response.status);
                }
                const result = await response.json();

                // 检查后端返回的成功标志
                if (!result.success) {
                    throw new Error(result.message || '用户数据获取失败');
                }

                return result.data;
            } catch (error) {
                console.error('API请求错误:', error);
                throw error;
            }
        }

        // 加载用户信息
        async function loadUserData() {
            //'正在从后端加载用户数据...'
            const profileLoading = document.getElementById('profileLoading');
            //用于显示错误信息的容器
            const errorContainer = document.getElementById('errorContainer');
            //用户资料表单
            const profileForm = document.getElementById('profileForm');

            try {
                const userData = await fetchUserData();

                // 更新侧边栏用户信息
                document.getElementById('username').textContent = userData.username;
                document.getElementById('userLevel').textContent = userData.level || '普通会员';
                document.getElementById('userAvatar').src = userData.avatarUrl || 'https://randomuser.me/api/portraits/men/32.jpg';

                // 更新表单数据
                document.getElementById('usernameInput').value = userData.username;
                document.getElementById('email').value = userData.email || '未设置';
                document.getElementById('phone').value = userData.phone || '未设置';
                document.getElementById('address').value = userData.address || '未设置地址';

                // 隐藏加载状态，显示表单
                profileLoading.style.display = 'none';
                profileForm.style.display = 'block';
                errorContainer.style.display = 'none';

            } catch (error) {
                console.error('加载用户数据失败:', error);
                profileLoading.style.display = 'none';
                profileForm.style.display = 'none';
                errorContainer.style.display = 'block';
                errorContainer.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${error.message || '加载用户信息失败，请稍后重试'}`;
            }
        }

        // 加载订单信息（真实数据）
        async function loadOrders() {
            const ordersLoading = document.getElementById('ordersLoading');
            const ordersContainer = document.getElementById('ordersContainer');

            try {
                const response = await fetch('/getOrderItemList');
                if (!response.ok) {
                    throw new Error('获取订单数据失败: ' + response.status);
                }
                const orderList = await response.json();

                if (!orderList || orderList.length === 0) {
                    ordersContainer.innerHTML = `
                        <div style="text-align: center; padding: 40px; color: #666;">
                            <div style="font-size: 3rem; margin-bottom: 10px;">📦</div>
                            <p>暂无订单记录</p>
                            <a href="product.html" style="color: #ff4400; text-decoration: none; margin-top: 10px; display: inline-block;">去购物</a>
                        </div>
                    `;
                    ordersLoading.style.display = 'none';
                    ordersContainer.style.display = 'block';
                    return;
                }

                // 按orderId分组
                const ordersMap = {};
                orderList.forEach(item => {
                    if (!ordersMap[item.orderId]) {
                        ordersMap[item.orderId] = {
                            id: item.orderId,
                            date: formatDate(item.createdAt),
                            status: getStatusText(item.status),
                            total: item.totalAmount,
                            products: []
                        };
                    }
                    ordersMap[item.orderId].products.push({
                        id: item.productId,
                        name: item.productName,
                        price: item.price,
                        quantity: item.quantity,
                        image: item.imageUrl || ''
                    });
                });
                const orders = Object.values(ordersMap);

                // 生成订单HTML
                let ordersHTML = '';
                orders.forEach(order => {
                    let productsHTML = '';
                    order.products.forEach(product => {
                        productsHTML += `
                    <div class="order-product">
                        <img src="${product.image}" alt="${product.name}" onerror="this.src=''">
                        <div>
                            <div style="font-weight: 500; margin-bottom: 5px;">${product.name}</div>
                            <div style="color: #666; font-size: 13px;">数量: ${product.quantity} &nbsp; | &nbsp; 单价: ¥${product.price.toFixed(2)}</div>
                            <div style="color: #ff4400; font-weight: 500; margin-top: 3px;">小计: ¥${(product.price * product.quantity).toFixed(2)}</div>
                        </div>
                    </div>
                    `;
                    });

                    ordersHTML += `
                <div class="order-item">
                    <div class="order-header">
                        <span class="order-number">订单号 #${order.id} &nbsp; | &nbsp; 下单日期: ${order.date}</span>
                        <span class="order-status ${order.status.class}">${order.status.text}</span>
                    </div>
                    <div class="order-products">
                        ${productsHTML}
                    </div>
                    <div class="order-total">总计: ¥${order.total.toFixed(2)}</div>
                </div>
                `;
                });

                ordersContainer.innerHTML = ordersHTML;
                ordersLoading.style.display = 'none';
                ordersContainer.style.display = 'block';

            } catch (error) {
                console.error('加载订单数据失败:', error);
                ordersLoading.innerHTML =
                    '<div style="color: #ff4400; text-align: center;">加载订单数据失败，请稍后重试</div>';
            }
        }

        // 格式化日期
        //"2023-01-15T14:30:00Z" → "2023/01/15 22:30" (UTC+8时区)
        function formatDate(dateString) {
            if (!dateString) return '未知时间';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 获取订单状态文本
        function getStatusText(status) {
            const statusMap = {
                0: { text: '未配送', class: 'not-shipped' },
                1: { text: '已配送', class: 'shipped' },
            };
            return statusMap[status] || { text: '未知状态', class: '' };
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function () {
            // 加载用户数据
            loadUserData();

            // 检查URL锚点，决定显示哪个页面
            const hash = window.location.hash;
            // 锚点为#orders时，显示订单页面  data-content 属性决定要显示哪个页
            if (hash === '#orders') {
                // 直接显示订单页面
                document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
                document.querySelector('[data-content="orders"]').classList.add('active');
                document.getElementById('profileContent').classList.remove('active');
                document.getElementById('ordersContent').classList.add('active');
                // 加载订单数据
                loadOrders();
            }

            // 菜单切换功能
            document.querySelectorAll('.menu-item').forEach(item => {
                item.addEventListener('click', function () {
                    document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
                    this.classList.add('active');

                    if (this.dataset.content === 'profile') {
                        document.getElementById('profileContent').classList.add('active');
                        document.getElementById('ordersContent').classList.remove('active');
                    } else if (this.dataset.content === 'orders') {
                        document.getElementById('profileContent').classList.remove('active');
                        document.getElementById('ordersContent').classList.add('active');

                        // 第一次切换到订单页面时加载订单数据
                        if (!document.getElementById('ordersContainer').dataset.loaded) {
                            loadOrders();
                            document.getElementById('ordersContainer').dataset.loaded = 'true';
                        }
                    }
                });
            });

            // 编辑按钮
            document.getElementById('editButton').addEventListener('click', function () {
                // 启用表单编辑
                document.querySelectorAll('#profileForm input').forEach(input => {
                    if (input.id !== 'usernameInput') { // 用户名不可修改
                        input.readOnly = false;
                    }
                });

                // 切换按钮状态
                document.getElementById('editButton').style.display = 'none';
                document.getElementById('saveButton').style.display = 'inline-block';
                document.getElementById('editButtonText').textContent = '取消编辑';
            });

            // 保存逻辑
            document.getElementById('saveButton').addEventListener('click', async function () {
                const userData = {
                    username: document.getElementById('usernameInput').value,
                    email: document.getElementById('email').value,
                    phone: document.getElementById('phone').value,
                    address: document.getElementById('address').value
                };

                try {
                    const response = await fetch('/updateUserInfo', {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(userData)
                    });

                    const result = await response.json();

                    if (result.success) {
                        showNotification('保存成功', '您的信息已更新');
                        // 退出编辑模式
                        exitEditMode();
                    } else {
                        throw new Error(result.message || '保存失败');
                    }
                } catch (error) {
                    console.error('保存失败:', error);
                    showNotification('保存失败', error.message, true);
                }
            });

            // 退出编辑模式函数
            function exitEditMode() {
                document.querySelectorAll('#profileForm input').forEach(input => {
                    input.readOnly = true;
                });
                document.getElementById('editButton').style.display = 'inline-block';
                document.getElementById('saveButton').style.display = 'none';
                document.getElementById('editButtonText').textContent = '编辑资料';
            }

            // 消息提示函数
            function showNotification(title, message, isError = false) {
                const notification = document.createElement('div');
                notification.style.position = 'fixed';
                notification.style.top = '20px';
                notification.style.right = '20px';
                notification.style.backgroundColor = isError ? '#ffebee' : '#e8f5e9';
                notification.style.color = isError ? '#c62828' : '#2e7d32';
                notification.style.padding = '15px 20px';
                notification.style.borderRadius = '4px';
                notification.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
                notification.style.zIndex = '1000';
                notification.style.transition = 'opacity 0.3s ease-out';
                notification.innerHTML = `
                <strong>${title}</strong><br>
                ${message}
            `;

                document.body.appendChild(notification);

                // 3秒后淡出
                setTimeout(() => {
                    notification.style.opacity = '0';
                    setTimeout(() => {
                        notification.remove();
                    }, 300);
                }, 3000);
            }
        });
    </script>
</body>

</html>